<script setup lang="ts">
import { defineEmits, defineProps, ref, onMounted} from 'vue';
import { useNotification} from "naive-ui";
import {getVerifyCodeAPI,  updateUser2FAMethod, verify2FACorrect, updateEmailAccount, loginVerifyAPI, getUserDetail } from "@/api"
import {resultCodeNotify} from "@/utils/rest/notifyHint";
import { useUserStore } from "@/store";
import { QrcodeImg} from '@/components/common'

const emit = defineEmits(['dialog-closed']);
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  different: {
    type: Number,
    default: 0
  }
})
const initSecond = ref<number>(0);
const sendType = 3;
const hint = useNotification();
const userStore = useUserStore();

const bindFrom = ref({account: "", pwd: "", source: 0})
const vaildAccount = ref<number>(0);                            // 账号提示框
const vaildPwd = ref<number>(0) ;                               // 密码 或 验证码提示
const timer = ref<ReturnType<typeof setInterval> | null>(null); // 初始化计时器引用
const different = ref<number>(0);

/**
 *  初始化
 */
onMounted(() => {
  different.value = props.different
  if (different.value == 2) {
    createQrcode()
  }
})

/**
 * 初始化提示值
 */
function initHintParam(){
  vaildPwd.value = 0;
  vaildAccount.value = 0;
}
/**
 *  验证绑定数据是否符合
 */
function vailAccountVerify() {
  initHintParam()
  let verifyCode = false;
  verifyCode = vailAccountMethod() || verifyCode
  if (bindFrom.value.pwd === '') {
    vaildPwd.value = 1;
    verifyCode = verifyCode || true;
  }
  return verifyCode;
}

/**
 *  邮箱账号验证
 */
function vailAccountMethod() {
  vaildAccount.value = 0;
  if(bindFrom.value.account === '') {
    vaildAccount.value = 1;
    return true;
  }
  const emailRegex = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
  if (!emailRegex.test(bindFrom.value.account)) {
    bindFrom.value.source = 1;
  } else {
    bindFrom.value.source = 0;
  }
  return false
}

/**
 * 获取验证码
 */
async function getVerifyCodeBtn() {
  if (vailAccountMethod()) {
    return
  }
  await getVerifyCodeAPI({
    account: bindFrom.value.account,
    source: bindFrom.value.source,
    type:  sendType
  }).then(res => {
    resultCodeNotify(hint,  "验证码发送", res)
    if (res.code === 200) {
      timerStart();
    }
  }).catch(error => {
    resultCodeNotify(hint,  "验证码发送", error)
  })
}

/**
 * 倒计时
 */
function timerStart() {
  initSecond.value = 60;
  timer.value = setInterval(() => {
    if (initSecond.value > 0) {
      initSecond.value--;
    } else {
      clearInterval(timer.value);
    }
  }, 1000);
}

/**
 * 关闭
 */
function closeDialog() {
  emit('dialog-closed')
}

/**
 *  提交
 */
function submitRequest() {
  const different = props.different;
  switch (different) {
    case 0:

      break;
    case 1:
      updateEmailCorrection()
      break;
    case 2:
      bind2FACorrection()
      break
    default:

  }
}

/**
 *  修改2fa 验证码
 */
function bind2FACorrection() {
  bindFrom.value.source = 1
  verify2FACorrect(bindFrom.value).then(res => {
    if (res.code === 200) {
      resultCodeNotify(hint,  "2FA修改", res)
      getUserDetail()
      emit('dialog-closed')
    }
  })
}

/**
 * 修改邮箱账号
 */
function updateEmailCorrection() {
  vailAccountVerify()
  updateEmailAccount(bindFrom.value).then(res => {
    if (res.code === 200) {
      resultCodeNotify(hint, "", res)
      getUserDetail()
      emit("dialog-closed")
    }
  })
}

/**
 * 生成二维码
 */
const qrCodeData = ref('');
function createQrcode() {
  try {
    updateUser2FAMethod().then(async res => {
      if (res.code === 200) {
        qrCodeData.value = res.data.dataMessage;
      }
    })
  } catch (error) {
    console.error('生成二维码时出错:', error);
  }
}

</script>

<template>
  <div class="dialog-page" @click.stop.prevent="closeDialog">

    <div class="dialog-content w-96 rounded" @click.stop>
      <p class="text-center fs-5 text-primary mt-3 fw-bold">{{title}}</p>

      <div v-if="different !== 2" class="input-material-group mb-3 col-10 mx-auto">
        <input
            v-model="bindFrom.account"
            class="input-material"
            placeholder="输入账号"/>
        <span v-if="vaildAccount === 1" class="hint-text">账号为空哦</span>
      </div>

      <div  v-if="different === 2" class="input-material-group mb-3 col-10 mx-auto">
        <div>
          <div class="col-8 mx-auto text-center text-danger"> 使用2FA验证器扫一扫</div>
          <div v-if="qrCodeData" class="qr-code-container">
            <QrcodeImg :qrcode="qrCodeData" width="200" color="#2F80ED" bgcolor="f1f1f1" />
          </div>
        </div>
      </div>

      <div class="input-material-group mb-3 col-10 mx-auto">
        <div class="d-flex">
          <input
              v-model="bindFrom.pwd"
              class="input-material"
              placeholder="验证码"/>
          <NButton v-if="different !== 2" class="send-code-btn" color="#2F80ED" @click="getVerifyCodeBtn" :disabled="initSecond > 0">
            <span v-if="initSecond == 0">验证码</span>
            <span v-if="initSecond > 0">{{initSecond}}后重发</span>
          </NButton>
        </div>
        <span v-if="vaildPwd == 1" class="hint-text">密码不能为空哦</span>
      </div>
      <div class="input-material-group mb-5 col-10 mx-auto">
        <div class="float-right d-flex">
          <NButton color="#9E9D9D" @click="closeDialog" >
            关闭
          </NButton>
          <p class="w-5"></p>
          <NButton color="#2F80ED" @click="submitRequest">
            确认
          </NButton>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
body, html {
  margin: 0;
  width: 100%;
  height: 100%; /* 确保body和html有全屏高度 */
}
.dialog-page {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex; /* 添加Flexbox布局 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 99;
}

.qr-code-container {
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-content {
   border-radius: 5px;
   background-color: #f1f1f1;
}
.input-material-group {
  position: relative;
  padding-top: 0.85rem
}
.input-material-group .input-material {
  letter-spacing: 1px;
  border: none;
  outline: none;
  background: none;
  padding: .375rem 0;
  border-bottom: 1px solid #40444b;
  display: block;
  width: 100%;
}
.send-code-btn {
  position: absolute;
  right: 10px;
  top: 5px
}
.hint-text {
  color: red;
}
</style>

